package com.pb.infra.oth.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * zip通用类
 *
 * @author liudebao
 * @date 2020/4/10
 */
@Slf4j
public class ZipUtil {
    private ZipUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 将多个文件压缩成zip
     *
     * @param files
     * @param zipFile
     */
    public static void zip(List<File> files, File zipFile) {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            for (File file : files) {
                zip(file, out);
            }
        } catch (IOException e) {
            log.error("failed to zip", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("failed to zip", e);
                }
            }
        }
    }

    /**
     * 压缩
     *
     * @param file
     * @param out
     * @throws IOException
     */
    public static void zip(File file, ZipOutputStream out) {
        if (file.exists()) {
            FileInputStream in = null;
            try {
                byte[] buf = new byte[BUFFER_SIZE];
                out.putNextEntry(new ZipEntry(file.getName()));
                in = new FileInputStream(file);
                int len;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
                out.flush();
                out.closeEntry();
                in.close();
            } catch (IOException e) {
                log.error("failed to zip", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        log.error("failed to zip", e);
                    }
                }
            }
        }
    }
}
